package com.cube.share.idempotence.service;

import com.cube.share.base.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author litb
 * @date 2021/3/11 15:30
 * @description 幂等性token Service
 */
@Service
@Slf4j
public class IdempotenceTokenService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取幂等性token,执行成功后会在redis中存入 prefix+token:value一条记录
     *
     * @param value 存入redis中的value
     * @return
     */
    public String generateIdempotenceToken(String value) {
        String token = UUID.randomUUID().toString();
        String key = Constant.IDEMPOTENCE_TOKEN_PREFIX + token;
        stringRedisTemplate.opsForValue().set(key, value, 3, TimeUnit.MINUTES);
        return token;
    }
}
